import Login from '@/views/Login/index.vue'
import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
// 主界面框架（包含侧边栏+顶部栏，嵌套子路由）
import MainLayout from '@/views/Layout/index.vue'
// 功能页面
import Customer from '@/views/Customer/index.vue'
import Product from '@/views/Product/index.vue'
import Provide from '@/views/Provide/index.vue'
// 工单相关
import WorkOrderList from '@/views/WorkOrder/index.vue'
import WorkOrderDispatch from '@/views/WorkOrder/dispatch.vue'
//系统相关
import Permission from '@/views/Permission/index.vue'
import Role from '@/views/Permission/components/Role.vue'
import User from '@/views/Permission/components/User.vue'

const routes = [
  // 登录页（单独页面，无需布局）
  { path: '/login', component: Login, meta: { requiresAuth: false } },
  // 工单相关路由
  {
    path: '/work-order/list',
    name: 'WorkOrderList',
    component: WorkOrderList,
    meta: { requiresAuth: true }
  },
  // 添加工单派单路由
  {
    path: '/work-order/dispatch',
    name: 'WorkOrderDispatch',
    component: WorkOrderDispatch,
    meta: { requiresAuth: true }
  },
  //系统管理路由
  {
    path: '/permission',
    name: 'Permission',
    component: Permission,
    meta: { requiresAuth: true, role: ['admin'] }
  },
  {
    path: '/permission/role',
    name: 'Role',
    component: Role,
    meta: { requiresAuth: true, role: ['admin'] }
  },
  {
    path: '/permission/user',
    name: 'User',
    component: User,
    meta: { requiresAuth: true, role: ['admin'] }
  },
  // 主界面框架（需登录，嵌套所有功能页面）
  {
    path: '/',
    component: MainLayout,
    meta: { requiresAuth: true }
  },
  {
    path: '/customer/list',
    component: Customer,
    meta: { requiresAuth: true, role: ['admin'] }
  },
  // 供应商管理
  {
    path: '/provide/list',
    component: Provide,
    meta: { requiresAuth: true, role: ['admin'] }
  },
  // 产品管理相关路由
  {
    path: '/product',
    meta: { requiresAuth: true, role: ['admin'] },
    children: [
      {
        path: 'type-list',
        component: () => import('@/views/Product/components/TypeList.vue'),
        meta: { requiresAuth: true, role: ['admin'] }
      },
      {
        path: 'list',
        component: Product,
        meta: { requiresAuth: true, role: ['admin'] }
      },
      {
        path: 'create',
        component: () => import('@/views/Product/components/ProductForm.vue'),
        meta: { requiresAuth: true, role: ['admin'] }
      },
      {
        path: 'edit/:id',
        component: () => import('@/views/Product/components/ProductForm.vue'),
        meta: { requiresAuth: true, role: ['admin'] }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 添加路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  const requiresAuth = to.meta.requiresAuth !== false; // 默认需要认证

  // 获取本地存储的token
  const token = localStorage.getItem('token');

  // 如果需要认证但没有token，则跳转到登录页
  if (requiresAuth && !token) {
    // 记录当前要访问的路径，登录后可以跳回
    next({ path: '/login', query: { redirect: to.fullPath } });
  }
  // 如果已经登录但要访问登录页，则跳转到首页
  else if (!requiresAuth && token && to.path === '/login') {
    next('/');
  }
  // 角色权限检查
  else if (requiresAuth && token && to.meta.role) {
    const userRole = localStorage.getItem('userRole') || '';
    // 检查用户角色是否在允许的角色列表中
    if (to.meta.role.includes(userRole)) {
      next();
    } else {
      // 角色不匹配，跳转到首页或无权限页面
      next('/');
      ElMessage.error('您没有访问该页面的权限');
    }
  }
  // 其他情况直接放行
  else {
    next();
  }
});

export default router
